/**
 * Validation helpers and error handling utilities
 */

export interface HttpError extends Error {
  status?: number;
  code?: string;
}

/**
 * Sanitizes error messages to remove sensitive information
 */
export function sanitizeErrorMessage(message: string): string {
  // Remove potential API keys, tokens, or sensitive data patterns
  return message
    .replace(/api[_-]?key[s]?["\s]*[:=]["\s]*[a-zA-Z0-9_-]+/gi, 'api_key=***')
    .replace(/token[s]?["\s]*[:=]["\s]*[a-zA-Z0-9_.-]+/gi, 'token=***')
    .replace(/bearer\s+[a-zA-Z0-9_.-]+/gi, 'bearer ***')
    .replace(/password[s]?["\s]*[:=]["\s]*[^\s"]+/gi, 'password=***');
}

/**
 * Formats embedding errors with user-friendly messages
 */
export function formatEmbeddingError(error: any, maxRetries: number): Error {
  if (error instanceof Error) {
    const httpError = error as HttpError;
    
    // Handle specific HTTP status codes
    if (httpError.status === 401) {
      return new Error("Authentication failed. Please check your API key configuration.");
    }
    
    if (httpError.status === 403) {
      return new Error("Access forbidden. Please verify your API key permissions.");
    }
    
    if (httpError.status === 429) {
      return new Error(`Rate limit exceeded after ${maxRetries} retries. Please try again later.`);
    }
    
    if (httpError.status === 404) {
      return new Error("API endpoint not found. Please check your base URL configuration.");
    }
    
    if (httpError.status && httpError.status >= 500) {
      return new Error(`Server error (${httpError.status}). The embedding service may be temporarily unavailable.`);
    }
    
    // Return sanitized error message for other cases
    return new Error(sanitizeErrorMessage(error.message));
  }
  
  return new Error("An unknown error occurred during embedding generation.");
}

/**
 * Wraps async functions with standardized error handling
 */
export async function withValidationErrorHandling<T>(
  fn: () => Promise<T>,
  context: string
): Promise<{ valid: boolean; error?: string; result?: T }> {
  try {
    const result = await fn();
    return { valid: true, result };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    const sanitizedMessage = sanitizeErrorMessage(errorMessage);
    
    console.error(`[${context}] Validation error:`, sanitizedMessage);
    
    return {
      valid: false,
      error: `${context} validation failed: ${sanitizedMessage}`
    };
  }
}

/**
 * Validates that required environment variables are set
 */
export function validateRequiredEnvVars(requiredVars: string[]): { valid: boolean; missingVars?: string[] } {
  const missingVars = requiredVars.filter(varName => !process.env[varName]);
  
  if (missingVars.length > 0) {
    return { valid: false, missingVars };
  }
  
  return { valid: true };
}

/**
 * Validates a URL format
 */
export function validateUrl(url: string): { valid: boolean; error?: string } {
  try {
    new URL(url);
    return { valid: true };
  } catch (error) {
    return { valid: false, error: `Invalid URL format: ${url}` };
  }
}

/**
 * Validates file extension against supported extensions
 */
export function validateFileExtension(filePath: string, supportedExtensions: string[]): boolean {
  const ext = filePath.toLowerCase().split('.').pop();
  return ext ? supportedExtensions.includes(`.${ext}`) : false;
}
